import os
from threading import Thread
import random
import json
import uuid
from flask import render_template, request

import helper
import jieba_fenci
from vender import aip_baidu
from vender import tuling
import constants
from flask.views import MethodView
from globals import r, config


class IndexView(MethodView):
    def get(self):
        return render_template("index.html")


class TaskView(MethodView):
    def post(self):
        task_id = request.form.get("task_id")
        state = r.blpop(task_id, timeout=6)
        if not state:
            return json.dumps({"state": '1'})
        else:
            state = bytes.decode(state[1])

        if state == "1":
            return json.dumps({"state": state})
        elif state == "2":
            return json.dumps({"state": state, 'success_msg': constants.SUCCESS_MSG})
        elif state == "3":
            return json.dumps({"state": state, 'error_msg': constants.ERROR_MSG})


class UploadView(MethodView):
    def post(self):
        file_info = request.values.to_dict()
        file_name = file_info["name"]
        audio_file = request.files["file"]
        rom_num = str(random.randint(1, 20))
        audio_file.save(os.path.join(config.file_path, "static", "audio", rom_num, file_name))
        res_text = aip_baidu.audio_to_text(os.path.join(config.file_path, "static", "audio", rom_num, file_name))

        task_info = jieba_fenci.fenci(res_text["result"][0])
        if task_info[1]:
            task = task_info[0]
            task_id = str(uuid.uuid1())
            func = helper.get_function(task.get("task_id"))
            func.apply_async(args=[task_id])
            return json.dumps({"success_msg": task.get("success_msg"), "task_id": task_id})

        res_str = tuling.tl(res_text["result"][0], str(uuid.uuid1()))
        res_file_name = aip_baidu.text_to_audio(res_str)

        res_json = json.dumps({
            "ret_msg": res_file_name
        })

        return res_json
